package com.job.client.message.listener;

import com.alibaba.fastjson2.JSON;
import com.job.client.common.exception.MyselfException;
import com.job.client.common.minio.BucketNameConstant;
import com.job.client.common.minio.MinIOUtils;
import com.job.client.common.result.ResponseResult;
import com.job.client.common.utils.DateTimeUtils;
import com.job.client.message.mapper.NoticeMapper;
import com.job.client.model.message.constant.FreemarkerConstant;
import com.job.client.model.message.constant.NoticeConstant;
import com.job.client.model.message.pojo.Notice;
import com.job.client.model.rabbitmq.MessageConstant;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
@Slf4j
public class NoticeListener {
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Autowired
    private NoticeMapper noticeMapper;

    @RabbitListener(queues = MessageConstant.QUEUE_MESSAGE_AVATAR)
    public void avatarMessage(String dataJSON){
        saveNotice(dataJSON, NoticeConstant.CATEGORY_AVATAR);
    }
    @RabbitListener(queues = MessageConstant.QUEUE_MESSAGE_POSTS)
    public void postsMessage(String dataJSON){
        saveNotice(dataJSON, NoticeConstant.CATEGORY_POSTS);
    }
    @RabbitListener(queues = MessageConstant.QUEUE_MESSAGE_COMPANY)
    public void companyMessage(String dataJSON){
        saveNotice(dataJSON, NoticeConstant.CATEGORY_COMPANY);
    }
    public void saveNotice(String dataJSON,String category){
        HashMap<String,String> data = JSON.parseObject(dataJSON, HashMap.class);
        String result = data.get("result"); //结果
        String userId = data.get("userId"); //用户id
        String reason = data.get("reason"); //获得失败原因
        String type = "";
        if(NoticeConstant.CATEGORY_AVATAR.equals(category)){
            type=NoticeConstant.TYPE_AVATAR;
        }else if(NoticeConstant.CATEGORY_POSTS.equals(category)){
            type=NoticeConstant.TYPE_POSTS;
        }else if(NoticeConstant.CATEGORY_COMPANY.equals(category)){
            type=NoticeConstant.TYPE_COMPANY;
        }
        String title="【"+type+"】 "+type+"结果通知";
        String createTime = DateTimeUtils.createNowTime();
        Map<String,String> init = new HashMap<>();
        init.put("userId",userId);
        init.put("title",title);
        init.put("result",result);
        init.put("reason",reason);
        init.put("time",createTime);
        String url = noticeInit(init);
        if(url == null){
            new MyselfException(201,"freemarker生成模板文件保存到minio失败");
            return;
        }
        Notice notice = new Notice(userId,title,type,url,createTime);
        noticeMapper.insert(notice);
    }
    public String noticeInit(Map<String,String> data) {
        Configuration cfg = freeMarkerConfigurer.getConfiguration();
//        Writer out = null;
        StringWriter out = new StringWriter();
        String fileName = String.valueOf(UUID.randomUUID()) +".html";
        File file = new File(FreemarkerConstant.NOTICE_URL+fileName);
        try {
            cfg.setDefaultEncoding(StandardCharsets.UTF_8.name());
            Template template = cfg.getTemplate("notice.ftl");
//            out = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
            template.process(data, out);
            log.info("生成静态html,路径：{}", FreemarkerConstant.NOTICE_URL+fileName);
            // 文件保存到minio中
            //转换成字节流
            InputStream is = new ByteArrayInputStream(out.toString().getBytes());
            MinIOUtils.uploadFile(BucketNameConstant.CLIENT_MESSAGE,fileName,is,"text/html");
            String url = MinIOUtils.getBasisUrl(BucketNameConstant.CLIENT_MESSAGE, fileName);
            return url;
        } catch (Exception e) {
            log.error("生成html静态文件失败", e);
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    log.error("流关闭失败", e);
                }
            }
        }
        return null;
    }
}
